import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/status.dart' as status;

class WebSocketTestRoute extends StatefulWidget {
  const WebSocketTestRoute({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _WebSocketTestRouteState();
}

class _WebSocketTestRouteState extends State<WebSocketTestRoute> {
  final TextEditingController _controller = TextEditingController();

  late IOWebSocketChannel channel;

  String _text = "";

  @override
  void initState() {
    super.initState();
    channel =
        IOWebSocketChannel.connect('ws://127.0.0.1:8011/ping');
    channel.stream.listen((message) {
      _text = "echo: $message";
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Web Socket Test'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: <Widget>[
            Form(
              child: TextFormField(
                controller: _controller,
                decoration: const InputDecoration(labelText: 'Send a message'),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 24.0),
              child: Text(_text),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          if (_controller.text.isNotEmpty) {
            channel.sink.add(_controller.text);
          }
        },
        tooltip: 'Send message',
        child: const Icon(Icons.send),
      ),
    );
  }

  @override
  void dispose() {
    channel.sink.close();
    super.dispose();
  }
}
